﻿using B.S.Shop.Application.Command;
using B.S.Shop.Domain;
using B.S.Shop.ErrorCode;
using B.S.Shop.Infartructrue.Interfaces;
using MediatR;

namespace B.S.Shop.Application.Commandhandler
{
    public class ShopQueryCommandhandler : IRequestHandler<ShopQueryCommand, APIResult<APIPageing<List<ShopClass>>>>
    {
        public ShopQueryCommandhandler(IBaseRepository<ShopClass> shopRepository)
        {
            ShopRepository = shopRepository;
        }

        public IBaseRepository<ShopClass> ShopRepository { get; }

        public async Task<APIResult<APIPageing<List<ShopClass>>>> Handle(ShopQueryCommand request, CancellationToken cancellationToken)
        {
            var path = ShopRepository.GetAll();
            if(!string.IsNullOrEmpty(request.ShopName))
            {
                path = path.Where(a => a.ShopName.Contains(request.ShopName));
            }
            if(!string.IsNullOrEmpty(request.ShopCord))
            {
                path = path.Where(a => a.ShopCord.Contains(request.ShopCord));
            }
            if(request.IsOpone!=null)
            {
                path = path.Where(a => a.IsShop == request.IsOpone);
            }
            if(!string.IsNullOrEmpty(request.StartTime))
            {
                path = path.Where(a => a.ShopTime >= Convert.ToDateTime(request.StartTime));
            }
            if(!string.IsNullOrEmpty(request.EndTime))
            {
                path = path.Where(a => a.ShopTime <= Convert.ToDateTime(request.EndTime).AddDays(1));
            }

            var TotalCount=path.Count();
            var PageCount = (int)Math.Ceiling(TotalCount * 1.0 / request.PageSize);
            var list = path.OrderBy(a => a.ShopId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            return new APIResult<APIPageing<List<ShopClass>>>()
            {
                Code = ResultCode.success,
                Mag = "",
                data = new APIPageing<List<ShopClass>>
                {
                    TotalCount = TotalCount,
                    PageCount = PageCount,
                    Data = list
                }
            };
        }
    }
}
